package com.hsgene.user.controller;

import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.resolver.IgnoreUserToken;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.user.dto.account.AccountPasswordInitializationDto;
import com.hsgene.user.exception.UserErrorCode;
import com.hsgene.user.service.OperationAccountService;
import com.hsgene.user.service.api.SecurityService;
import com.hsgene.user.session.UserSessionComponent;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 密码管理
 *
 * @author wangbing
 * @version 1.0, 2018/7/31
 */
@RestController
@RequestMapping("/1.0/genetic/testing")
public class GeneticPasswordController {

    @Resource
    private SecurityService securityService;

    @Resource
    private OperationAccountService operationAccountService;

    @Resource
    private UserSessionComponent userSessionComponent;

    /**
     * 管理员用户第一次登录修改密码
     *
     * @param initialization 后台用户第一次登录强制修改密码信息DTO
     * @param userInfo
     * @return 操作结果
     */
    @IgnoreUserToken(platform = 1)
    @PutMapping("account/password/initialization")
    public ApiResult<NullObject> initAccountPwd(
            @RequestBody AccountPasswordInitializationDto initialization,
            @FromSession UserInfo userInfo, HttpSession session) {
        if (userInfo == null) {
            return ApiResult.fail(UserErrorCode.USER_NOT_LOGIN);
        }
        if (!userInfo.getExtra().getFirstLogin() || !initialization.getPwdInitToken().equals(userInfo.getExtra().getPwdInitToken())) {
            return ApiResult.fail(UserErrorCode.FIRST_LOGIN_VERIFY_ERROR);
        }
        ApiResult<String> decryptedResult = securityService.rsaDecrypt(initialization.getPwd());
        if (!decryptedResult.isSucc()) {
            return ApiResult.fail(decryptedResult.getError());
        }
        String decryptedPwd = decryptedResult.getData();
        ApiResult<NullObject> result = operationAccountService.updateOperationAccountPwd(userInfo.getUserId(), decryptedPwd, true);
        if (result.isSucc()) {
            userSessionComponent.remove(session, userInfo);
        }
        return result;
    }
}
